<template>
  <div class="publicBox bindEmail">
    <bindInfoContentComponent slot="content" :data="data">
      <span slot="infoContent">
        <span class="tips" :class="{ haveData: userInfo.email }">{{
          `${
            userInfo.email ? userInfo.email : "未绑定（绑定邮箱可获得1积分）"
          }` | filterString(showDetail)
        }}</span>
        <span v-if="userInfo.email">
          <img :src="require('@/assets/images/nsee.png')" class="eyeIcon" v-if="showDetail" @click="showDetail = false"  />
          <img :src="require('@/assets/images/see.png')" class="eyeIcon" @click="showDetail = true" v-else />
        </span>
      </span>
      <button @click="handelShowDialog" slot="button">
        {{ `${userInfo.email ? "更换" : "绑定"}` }}
      </button>
    </bindInfoContentComponent>
    <el-dialog
      title="绑定邮箱"
      :visible.sync="dialogVisible"
      ref="dialog"
      :close-on-click-modal="false"
      @close="changeClose"
    >
      <template slot="title">
        <div class="headTitle" v-if="!updatePass">
          {{ userInfo.email ? "更换邮箱" : "绑定邮箱" }}
        </div>
        <div v-else />
        <img
          :src="require('@/assets/images/delete.png')"
          @click="handelClose"
        />
      </template>
      <el-form
        :model="bindForm"
        :rules="bindRules"
        ref="form"
        v-if="dialogVisible && !userInfo.email && !updatePass"
        label-width="79px"
        :label-position="'right'"
      >
        <el-form-item label="邮箱：" prop="email" :error="emailErrorMessage">
          <el-input
            v-model="bindForm.email"
            @keypress.enter.native.prevent
            placeholder="请输入绑定的邮箱"
            @change="handleChangeEmail"
          ></el-input>
          <div class="tips fetchCodeBtn" @click="checkEmailField">
            点击获取验证码
          </div>
        </el-form-item>
        <el-form-item label="验证码：" prop="code">
          <el-input
            v-model.number="bindForm.code"
            @keypress.enter.native.prevent
            placeholder="请输入验证码"
          ></el-input>
          <div class="tips">
            {{ codeLastTime ? `重新发送 (${codeLastTime}s)` : "" }}
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handelConfirm">确 定</el-button>
          <el-button @click="handelCancel">取 消</el-button>
        </el-form-item>
      </el-form>
      <el-form
        :model="updateForm"
        :rules="updateRules"
        ref="form"
        v-if="dialogVisible && userInfo.email && !updatePass"
        label-width="79px"
        :label-position="'right'"
      >
        <!-- <el-form-item label="密码：" prop="password">
          <el-input
            type="password"
            show-password
            v-model="updateForm.password"
            @keypress.enter.native.prevent
            placeholder="请输入密码"
          ></el-input>
          <div class="tips" />
        </el-form-item> -->
        <el-form-item label="旧邮箱：" prop="email">
          <el-input
            v-model="updateForm.email"
            @keypress.enter.native.prevent
            placeholder="请输入新的邮箱"
          ></el-input>
          <div class="tips fetchCodeBtn" @click="checkEmailField">
            点击获取验证码
          </div>
        </el-form-item>
        <el-form-item label="验证码：" prop="code" :error="codeErrorMessage">
          <el-input
            v-model.number="updateForm.code"
            @keypress.enter.native.prevent
            placeholder="请输入验证码"
          ></el-input>
          <div class="tips">
            {{ codeLastTime ? `重新发送 (${codeLastTime}s)` : "" }}
          </div>
        </el-form-item>
        <el-form-item label="新邮箱：" prop="nEmail" :error="emailErrorMessage">
          <el-input
            v-model="updateForm.nEmail"
            @keypress.enter.native.prevent
            placeholder="请输入新的邮箱"
            @change="handleChangeEmail"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="确认邮箱："
          prop="nEmailConfirm"
          :error="nEmailErrorMessage"
        >
          <el-input
            v-model="updateForm.nEmailConfirm"
            @keypress.enter.native.prevent
            placeholder="请再次输入新的邮箱"
            @change="handleChangeEmail"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handelConfirm">确 定</el-button>
          <el-button @click="handelCancel">取 消</el-button>
        </el-form-item>
      </el-form>
      <div v-if="updatePass" class="successBox">
        <div>
          <img :src="require('@/assets/images/like.png')" class="passIcon" />
          {{ `邮箱${userInfo.email ? "修改" : "绑定"}成功！` }}
        </div>
        <div>
          <el-button type="primary" @click="handelCancel">确 定</el-button>
          <span class="timer">{{
            autoClouselastTime ? `${autoClouselastTime}s后自动关闭` : ""
          }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import {
  updateUserInfo,
  sendVaildCode,
  checkVaildCode,
  isExist,
} from "@/request/user";
import { throttle } from "@/util/tool";
const bindInfoContentComponent = () =>
  import("@/views/user/user/accountBindComponent/bindInfoContentComponent");
export default {
  // 组件销毁前清除定时器
  beforeDestroy() {
    clearInterval(this.lastTimer);
    clearInterval(this.autoCloseDialogTimer);
  },
  components: {
    bindInfoContentComponent
  },
  data() {
    const mailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    var checkEmail = (rule, value, callback) => {
      // 如果已经验证过 邮箱已被注册 则返回
      if (this.checkEmail === false) {
        this.emailErrorMessage = "";
        this.$nextTick(() => {
          callback(new Error("邮箱已被注册"));
        });
        return;
      }
      if (!mailReg.test(value)) {
        callback(new Error("请输入正确的邮箱格式"));
      } else {
        callback();
      }
    };
    var NcheckEmail = (rule, value, callback) => {
      if (this.userInfo.email) {
        if (this.userInfo.email === this.updateForm.nEmail) {
          this.emailErrorMessage = "";
          this.$nextTick(() => {
            callback(new Error("新邮箱与旧邮箱相同"));
          });
          return;
        }
      }
      // 如果已经验证过 邮箱已被注册 则返回
      if (this.checkEmail === false) {
        this.emailErrorMessage = "";
        this.$nextTick(() => {
          callback(new Error("邮箱已被注册"));
        });
        return;
      }
      if (!mailReg.test(value)) {
        callback(new Error("请输入正确的邮箱格式"));
      } else {
        callback();
      }
    };
    var NcheckNEmail = (rule, value, callback) => {
      if (!this.updateForm.nEmail) {
        if (this.userInfo.email === this.updateForm.nEmailConfirm) {
          this.nEmailErrorMessage = "";
          this.$nextTick(() => {
            callback(new Error("新邮箱与旧邮箱相同"));
          });
          return;
        }
        if (!mailReg.test(value)) {
          callback(new Error("请输入正确的邮箱格式"));
          return
        }
      }
      if (this.updateForm.nEmail !== this.updateForm.nEmailConfirm) {
        callback(new Error("与新的邮箱不一致"));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      // 绑定邮箱表单数据
      bindForm: {
        email: "",
        code: "",
      },
      // 绑定邮箱表单验证
      bindRules: {
        email: [
          {
            required: true,
            message: "请输入邮箱地址",
            trigger: "blur",
          },
          {
            validator: checkEmail,
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur",
          },
        ],
      },
      // 修改邮箱表单数据
      updateForm: {
        // password: "",
        email: "",
        code: "",
        nEmail: "",
        nEmailConfirm: "",
      },
      // 修改邮箱表单验证
      updateRules: {
        // password: [
        //   {
        //     required: true,
        //     message: "密码不能为空",
        //     trigger: "blur",
        //   },
        // ],
        email: [
          {
            required: true,
            message: "请输入邮箱地址",
            trigger: "blur",
          },
          {
            // validator: checkEmail,
            type: "email",
            message: "请输入正确的邮箱",
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur",
          },
        ],
        nEmail: [
          {
            required: true,
            message: "请输入邮箱地址",
            trigger: "blur",
          },
          {
            validator: NcheckEmail,
            trigger: "blur",
          },
        ],
        nEmailConfirm: [
          {
            required: true,
            message: "请输入邮箱地址",
            trigger: "blur",
          },
          {
            validator: NcheckNEmail,
            trigger: "blur",
          },
        ],
      },
      codeLastTime: 0, // 验证码倒计时
      lastTimer: null, // 定时器
      updatePass: false, // 更新成功
      autoClouselastTime: 0, // 自动关闭时间
      autoCloseDialogTimer: null, // 自动关闭定时器
      showDetail: true,
      codeErrorMessage: "", // 验证码错误提示
      emailErrorMessage: "", // 邮箱验证信息
      nEmailErrorMessage: "", // 确认邮箱地址不一致
      checkEmail: null,
      data: {
        iconName: "iconemail1",
        title: "邮箱",
        tips: "可用邮箱加密码登录，可用邮箱找回密码"
      }
    };
  },
  props: {},
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  filters: {
    // 过滤字符串 加星号
    filterString(val, showDetail) {
      if (showDetail) {
        return val;
      } else {
        let sbStr = val.substring(0, val.indexOf("@"));
        let tail = val.substring(val.indexOf("@"));
        let rStr = "";
        if (sbStr.length > 3) {
          rStr = sbStr.substring(0, 3) + "***" + tail;
        } else {
          rStr = sbStr.substring(0, 1) + "***" + tail;
        }
        return rStr;
      }
    },
  },
  created() {
    if (this.userInfo.email) {
      this.updateForm.email = this.userInfo.email;
    }
  },
  methods: {
    // 打开弹出框
    handelShowDialog() {
      // if (this.userInfo.email) {
      //   this.$antdMessage.warning({
      //     content: '敬请期待!'
      //   })
      //   return
      // }
      this.dialogVisible = true;
    },
    // 关闭弹出框
    handelClose() {
      this.dialogVisible = false;
    },
    // 关闭弹窗回调
    changeClose() {
      this.updatePass = false;
    },
    // 取消
    handelCancel() {
      this.dialogVisible = false;
    },
    // 验证验证码是否正确checkCode
    handleCheckCode() {
      // 先清空错误提示 否则多次错误无法显示错误信息
      this.codeErrorMessage = "";
      let params = {
        userMail: this.userInfo.email
          ? this.updateForm.email
          : this.bindForm.email,
        code: this.userInfo.email ? this.updateForm.code : this.bindForm.code,
      };
      // debugger
      checkVaildCode(params).then((res) => {
        if (res.errno === 0) {
          this.handelSubmit();
        } else if (res.message === "验证码已失效！") {
          this.$nextTick(() => {
            this.codeErrorMessage = res.message || "验证码错误";
          });
        } else {
          this.$antdMessage.error({
            content: res.message,
          });
        }
      });
    },
    // 设置发送验证码剩余时间
    handleGetLastTime() {
      let sendRegCodeLastTime = localStorage.getItem("rRCLT");
      const currTime = new Date().getTime();
      if (sendRegCodeLastTime === null) {
        this.codeLastTime = 0;
        return;
      }
      if (currTime - sendRegCodeLastTime < 60000) {
        this.handelFetchCode(
          60 - Math.ceil((currTime - sendRegCodeLastTime) / 1000)
        );
      } else {
        localStorage.removeItem("rRCLT");
      }
    },
    // 获取验证码
    handelFetchCode(time) {
      this.showCodeTips = true;
      // 如果验证码已发送倒计时没结束则退出
      this.codeLastTime = time;
      let lassTimer = setInterval(() => {
        --this.codeLastTime;
        // 清除计时器
        if (this.codeLastTime === 0) {
          clearInterval(lassTimer);
          lassTimer = null;
          localStorage.removeItem("rRCLT");
        }
      }, 1000);
    },
    // 获取验证码
    // handelFetchCode(e) {
    //   // 如果验证码已发送倒计时没结束则退出
    //   if (this.codeLastTime) return;
    //   this.codeLastTime = 60;
    //   this.lastTimer = setInterval(() => {
    //     --this.codeLastTime;
    //     // 清除计时器
    //     if (this.codeLastTime === 0) {
    //       clearInterval(this.lastTimer);
    //       this.lastTimer = null;
    //     }
    //   }, 1000);
    // },
    // 确定
    handelConfirm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 信息校验成功
          this.handleCheckCode();
        } else {
          // 信息校验不通过
          return false;
        }
      });
    },
    // 提交数据
    handelSubmit() {
      let params = {
        user: {
          userID: this.userInfo.userID,
          email: this.userInfo.email
            ? this.updateForm.nEmail
            : this.bindForm.email,
        },
      };
      updateUserInfo(params).then((res) => {
        if (res.errno === 0) {
          this.$antdMessage.success({
            content: this.userInfo.email ? "已更换绑定的邮箱！" : "绑定成功！",
          });
          // 展示成功界面
          this.updatePass = true;
          // 打开自动关闭定时器
          this.handelAutoCloseTimer();
          // 重置表单
          this.$refs.form.resetFields();
          // 重新获取用户信息
          this.$store.dispatch("user/reacquireUserInfo", params.user);
        } else {
          this.$antdMessage.error({
            content: res.message || "邮箱绑定失败！",
          });
        }
      });
    },
    // 创建自动关闭dialog计时器
    handelAutoCloseTimer() {
      this.autoClouselastTime = 3;
      this.autoCloseDialogTimer = setInterval(() => {
        --this.autoClouselastTime;
        // 清除计时器
        if (this.autoClouselastTime === 0) {
          this.handelClose();
          clearInterval(this.autoCloseDialogTimer);
          this.autoCloseDialogTimer = null;
        }
      }, 1000);
    },
    // 验证邮箱字段
    checkEmailField() {
      this.$refs["form"].validateField("email", (res) => {
        // 如果返回的错误信息为空
        if (res === "") {
          this.sendCode();
        }
      });
    },
    // 发送验证码
    sendCode() {
      // // 查看剩余时间
      if (this.codeLastTime) return;
      const params = {
        userMail: this.userInfo.email
          ? this.updateForm.email
          : this.bindForm.email,
      };
      sendVaildCode(params).then((res) => {
        if (res.errno === 0) {
          this.$antdMessage.success({
            content: `验证码已发送至邮箱，验证码有效时间${
              res.data.duration / 60
            }分钟！`,
          });
          localStorage.setItem("rRCLT", new Date().getTime());
          this.handelFetchCode(60);
        } else {
          this.$antdMessage.error({
            content: res.message || res,
          });
        }
      });
    },
    // 输入邮箱
    handleChangeEmail() {
      this.checkEmail = null;
      // 验证邮箱字段
      this.$refs["form"].validateField("email", (res) => {
        // 如果返回的错误信息为空
        if (res === "") {
          if (this.userInfo.email === this.updateForm.nEmail) {
            this.emailErrorMessage = "";
            // this.nEmailErrorMessage = ""
            this.$nextTick(() => {
              this.emailErrorMessage = "新邮箱与旧邮箱相同";
            });
            return;
          }
          throttle(() => {
            this.emailErrorMessage = "";
            // this.nEmailErrorMessage = ""
            this.checkAccountNum({
              userName: this.userInfo.email
                ? this.updateForm.nEmail
                : this.bindForm.email,
            }).then((isPass) => {
              if (isPass) {
                this.emailErrorMessage = "";
                // this.nEmailErrorMessage = ""
                this.checkEmail = true;
              } else {
                this.emailErrorMessage = "邮箱已被注册";
                this.checkEmail = false;
              }
            });
          });
        }
      });
    },
    // 检查邮箱是否被使用
    checkAccountNum(data) {
      return new Promise((resvloe, reject) => {
        isExist(data).then((res) => {
          if (res.message && res.message === "用户名未存在") {
            resvloe(true);
          } else {
            resvloe(false);
          }
        });
      });
    },
  },
};
</script>

<style lang="stylus">
.bindEmail {
  .el-dialog__wrapper {
    .el-dialog {
      padding-bottom: 16px;
      width: 570px;
      min-height: 280px;
      // max-height: 315px;
      background-color: #ffffff;
      border-radius: 10px;

      .el-dialog__header {
        padding: 24px 36px 0 27px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        img {
          cursor: pointer;
        }

        .headTitle {
          font-family: Segoe UI;
          font-size: 20px;
          color: #666666;
        }

        .el-dialog__headerbtn {
          right: 36px;
          height: 26px;

          .el-dialog__close {
            display: none;
          }
        }
      }

      .el-dialog__body {
        padding: 27px 58px 0 74px;

        .el-form {
          .el-form-item {
            margin-bottom: 20px;

            // display: flex;

            // justify-content: flex-end;
            .el-form-item__label {
              padding-right: 9px;
              font-family: Segoe UI;
              font-size: 14px;
              color: #666666;
            }

            .el-form-item__label::before {
              display: none;
            }

            .el-form-item__content {
              display: flex;

              .el-input {
                width: 200px;
                height: 40px;

                .el-input__inner {
                  padding-left: 11px;
                  font-family: Segoe UI;
                  font-size: 14px;
                  color: #909090;
                }

                .el-input.is-active .el-input__inner, .el-input__inner:focus {
                  border-color: rgba(102, 102, 102, 0.4) !important;
                }
              }

              .tips {
                margin-left: 25px;
                width: 84px;
                font-family: Segoe UI;
                font-size: 12px;
                color: #c0c0c0;
              }

              .fetchCodeBtn {
                cursor: pointer;
              }

              .el-button--primary {
                padding: 0;
                margin-top: 6px;
                margin-left: 20px;
                width: 60px;
                height: 35px;
                background-color: #0e79c0;
                border-radius: 5px;
                font-family: Segoe UI;
                font-size: 16px;
                color: #ffffff;
              }

              .el-button--default {
                padding: 0;
                margin-top: 6px;
                margin-left: 40px;
                width: 60px;
                height: 35px;
                background-color: #ffffff;
                border-radius: 5px;
                border: solid 1px rgba(14, 121, 192, 0.55);
                font-family: Segoe UI;
                font-size: 16px;
                color: #0e79c0;
              }
            }
          }
        }

        .successBox {
          padding-top: 44px;
          padding-bottom: 23px;
          height: 183px;
          display: flex;
          flex-flow: column;
          justify-content: space-between;
          align-items: center;
          font-family: Segoe UI;
          font-size: 22px;
          color: #666666;

          .passIcon {
            width: 21px;
            height: 20px;
          }

          .el-button--primary {
            padding: 0;
            width: 60px;
            height: 35px;
            background-color: #0e79c0;
            border-radius: 5px;
            font-family: Segoe UI;
            font-size: 16px;
            color: #ffffff;
          }

          .timer {
            margin-left: 19px;
            font-family: Segoe UI;
            font-size: 12px;
            color: #666666;
          }
        }
      }
    }
  }
}
</style>